// 工作进度计划页面

let workPlanData = [];
let filteredData = [];

// 加载工作进度计划页面
function loadWorkPlanPage(container) {
    container.innerHTML = `
        ${createPageTitle('工作进度计划', 'fas fa-tasks')}
        ${createToolbar([
            '<button class="btn btn-primary" onclick="showAddWorkPlanModal()">',
            '<i class="fas fa-plus mr-2"></i>新增计划',
            '</button>',
            '<button class="btn btn-secondary" onclick="loadWorkPlanData()">',
            '<i class="fas fa-refresh mr-2"></i>刷新',
            '</button>',
            '<button class="btn btn-accent" onclick="exportWorkPlanData()">',
            '<i class="fas fa-download mr-2"></i>导出',
            '</button>'
        ])}
        <div id="work-plan-list">
            ${createWorkPlanTable()}
        </div>
    `;
    
    // 绑定搜索事件
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.addEventListener('input', debounce(handleWorkPlanSearch, 300));
    }
    
    // 加载数据
    loadWorkPlanData();
}

// 创建工作进度表格
function createWorkPlanTable() {
    const headers = ['机型', '工单号', '数量', '日期', '备注'];
    return createTable(headers, filteredData, [
        { type: 'primary', icon: 'edit', handler: 'editWorkPlan' },
        { type: 'error', icon: 'trash', handler: 'deleteWorkPlan' }
    ]);
}

// 加载工作进度数据
async function loadWorkPlanData() {
    try {
        const data = await workPlanAPI.getAll();
        workPlanData = data;
        filteredData = data;
        updateWorkPlanTable();
    } catch (error) {
        showError('加载数据失败');
    }
}

// 更新工作进度表格
function updateWorkPlanTable() {
    const tableContainer = document.getElementById('work-plan-list');
    if (tableContainer) {
        tableContainer.innerHTML = createWorkPlanTable();
    }
}

// 处理搜索
function handleWorkPlanSearch() {
    const query = document.getElementById('search-input')?.value?.trim() || '';
    
    if (!query) {
        filteredData = workPlanData;
    } else {
        filteredData = workPlanData.filter(item => 
            item.model?.toLowerCase().includes(query.toLowerCase()) ||
            item.workOrder?.toLowerCase().includes(query.toLowerCase()) ||
            item.remark?.toLowerCase().includes(query.toLowerCase())
        );
    }
    
    updateWorkPlanTable();
}

// 显示新增模态框
function showAddWorkPlanModal() {
    const content = `
        <form id="work-plan-form" class="space-y-4">
            ${createFormInput('机型', 'model', 'text', '', { required: true, placeholder: '请输入机型' })}
            ${createFormInput('工单号', 'workOrder', 'text', '', { required: true, placeholder: '请输入工单号' })}
            ${createFormInput('数量', 'quantity', 'number', '', { required: true, placeholder: '请输入数量' })}
            ${createFormInput('日期', 'date', 'date', '', { required: true })}
            ${createFormInput('备注', 'remark', 'textarea', '', { placeholder: '请输入备注信息' })}
        </form>
    `;
    
    showModal('新增工作进度计划', content, () => {
        const form = document.getElementById('work-plan-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {
                model: formData.get('model'),
                workOrder: formData.get('workOrder'),
                quantity: parseInt(formData.get('quantity')),
                date: formData.get('date'),
                remark: formData.get('remark')
            };
            
            createWorkPlan(data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('work-plan-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {
                    model: formData.get('model'),
                    workOrder: formData.get('workOrder'),
                    quantity: parseInt(formData.get('quantity')),
                    date: formData.get('date'),
                    remark: formData.get('remark')
                };
                
                createWorkPlan(data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 创建工作进度
async function createWorkPlan(data) {
    try {
        await workPlanAPI.create(data);
        showSuccess('创建成功');
        loadWorkPlanData();
    } catch (error) {
        showError('创建失败');
    }
}

// 编辑工作进度
function editWorkPlan(id) {
    const item = workPlanData.find(w => w.id === id);
    if (!item) {
        showError('记录不存在');
        return;
    }
    
    const content = `
        <form id="work-plan-edit-form" class="space-y-4">
            ${createFormInput('机型', 'model', 'text', item.model, { required: true })}
            ${createFormInput('工单号', 'workOrder', 'text', item.workOrder, { required: true })}
            ${createFormInput('数量', 'quantity', 'number', item.quantity, { required: true })}
            ${createFormInput('日期', 'date', 'date', item.date, { required: true })}
            ${createFormInput('备注', 'remark', 'textarea', item.remark || '')}
        </form>
    `;
    
    showModal('编辑工作进度计划', content, () => {
        const form = document.getElementById('work-plan-edit-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {
                model: formData.get('model'),
                workOrder: formData.get('workOrder'),
                quantity: parseInt(formData.get('quantity')),
                date: formData.get('date'),
                remark: formData.get('remark')
            };
            
            updateWorkPlan(id, data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('work-plan-edit-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {
                    model: formData.get('model'),
                    workOrder: formData.get('workOrder'),
                    quantity: parseInt(formData.get('quantity')),
                    date: formData.get('date'),
                    remark: formData.get('remark')
                };
                
                updateWorkPlan(id, data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 更新工作进度
async function updateWorkPlan(id, data) {
    try {
        await workPlanAPI.update(id, data);
        showSuccess('更新成功');
        loadWorkPlanData();
    } catch (error) {
        showError('更新失败');
    }
}

// 删除工作进度
function deleteWorkPlan(id) {
    showConfirmDialog('确定要删除这条记录吗？', async () => {
        try {
            await workPlanAPI.delete(id);
            showSuccess('删除成功');
            loadWorkPlanData();
        } catch (error) {
            showError('删除失败');
        }
    });
}

// 导出工作进度数据
function exportWorkPlanData() {
    if (filteredData.length === 0) {
        showWarning('没有数据可导出');
        return;
    }
    
    const exportData = filteredData.map(item => ({
        '机型': item.model,
        '工单号': item.workOrder,
        '数量': item.quantity,
        '日期': item.date,
        '备注': item.remark || ''
    }));
    
    exportToCSV(exportData, `工作进度计划_${formatDate(new Date(), 'YYYY-MM-DD')}.csv`);
    showSuccess('导出成功');
}

// 绑定到全局作用域
window.loadWorkPlanPage = loadWorkPlanPage;
window.showAddWorkPlanModal = showAddWorkPlanModal;
window.editWorkPlan = editWorkPlan;
window.deleteWorkPlan = deleteWorkPlan;
window.exportWorkPlanData = exportWorkPlanData;
